/*
  工具类与工具函数
*/

//获取系统信息
const os = require('os')
class System {
    constructor() {
        this.hostname = os.hostname() // 服务器名
        this.ip = this.getIPAdress() // 服务器IP
        this.node = 'node v12.18.1'
        this.location = __dirname.slice(0, __dirname.lastIndexOf('\\'))
        this.system = os.type() + ' ' + os.release()
        this.arch = os.arch()
        this.cpus = os.cpus().length
        this.uptime = parseInt(os.uptime() / 60 / 60)
        this.totalmem = parseInt((os.totalmem() - os.freemem()) / 1048576)
    }
    getIPAdress() { // 获取IP
        var interfaces = os.networkInterfaces()
        for (var devName in interfaces) {
            var iface = interfaces[devName]
            for (var i = 0; i < iface.length; i++) {
                var alias = iface[i]
                if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
                    return alias.address
                }
            }
        }
    }
} 
//格式化请求参数value值，使其符合sql查询字段规范
function objectToSqlString(da){
  for(let key in da){     
    if(da[key].constructor.toString().indexOf('Array') > 0){ //给sql的Array值转字符串并加''号
      da[key] = '\'' + da[key].toString() + '\''
    }else if(typeof da[key] === 'boolean'){//布尔值转存0、1
      da[key] = Number(da[key])
    }else if(typeof da[key] === 'string'){ //给sql的string值加''号
      da[key] = '\'' + da[key] + '\''
    }
  }
  return da
} 

//当前日期时间
function thisDate(){
  const d = new Date();
  return d.getFullYear()+''+ (d.getMonth() + 1)+''+ d.getDate()+''+d.getHours()+''+d.getMinutes()+''+d.getSeconds()
}

//用户响应数据
function verifyUserData({username,password},loginData){
  let resData = {} // 响应数据 
  /* 记录登录成功与否、记录用户名是否存在、记录密码是否正确（1：成功，0：失败） */
  const logAr = [[],[],[]]  
  loginData.forEach(function (item) {
    //记录是否登录成功
    if(username == item.username && password == item.password){
      logAr[0].push(1)  
      //添加登录成功返回头数据
      return resData = {
        data:{
          id:item.id,
          rid:item.rid,
          username:item.username,
          token:'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOjUwMCwicmlkIjowLCJpYXQiOjE1MTI1NDQyOTksImV4cCI6MTUxMjYzMDY5OX0.eGrsrvwHm-tPsO9r_pxHIQ5i5L1kX9RX444uwnRGaIM'
        },
        meta:{
          'status': 200,
          'message': '用户登录成功'
        }
      }
    }else{
      logAr[0].push(0)
    }     
    //记录用户名是否存在 
    if (username == item.username) {
      logAr[1].push(1)
      // 记录密码是否正确
      password == item.password ? logAr[2].push(1) : logAr[2].push(0)              
    } else {
      logAr[1].push(0)
    }
  })
  if (!logAr[0].includes(1) &&!logAr[1].includes(1)) {
    resData.meta = {
      'status': 400,
      'message': '用户名不存在'
    }
  } else if (!logAr[0].includes(1) &&!logAr[2].includes(1)) {
    resData.meta = {
      'status': 400,
      'message': '密码错误'
    }
  }
  return resData
}

module.exports = {
  objectToSqlString,
  System,
  thisDate,
  verifyUserData
}